//
//  RNavigationController.swift
//  CheckmeRing
//
//  Created by 董鹏 on 2022/2/14.
//

import UIKit

class RNavigationController: UINavigationController,UINavigationControllerDelegate,UIGestureRecognizerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.YCSetUI()
        self.setNavigationBarTitleTextAttributes()
    }
    
    // MARK: - UI方法
    // 左滑返回手势
    private func YCSetUI(){
        self.navigationBar.isTranslucent = false;
        self.navigationBar.setBackgroundColorAndshowdowColor(BackgroundColor: UIColor.white, showdowColor: UIColor.white)
        if self.responds(to: #selector(getter: interactivePopGestureRecognizer)){
            self.delegate = self
            self.interactivePopGestureRecognizer?.delegate = self
            self.interactivePopGestureRecognizer?.isEnabled = false
        }
    }
    
    /**
     * 设置navigationBar的字体
     */
    func setNavigationBarTitleTextAttributes(){
        let textColor = UIColor.black
        self.navigationBar.titleTextAttributes = {[
            NSAttributedString.Key.foregroundColor: textColor,
            NSAttributedString.Key.font: mediumFont(size: 18.0)!
        ]}()
    }
    
    // MARK: - UINavigationControllerDelegate
    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
        self.interactivePopGestureRecognizer?.isEnabled = true
    }
    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        self.interactivePopGestureRecognizer?.isEnabled = true;
    }
    
    // 解决在根目录下 界面卡死的 情况
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        if ( gestureRecognizer == self.interactivePopGestureRecognizer )
        {
            if (self.viewControllers.count < 2 || self.visibleViewController.hashValue == self.viewControllers.first.hashValue)
            {
                return false;
            }
        }
        return true;
    }

}

extension UINavigationBar {
    
    /// 设置导航栏背景
    public func setBackgroundColorAndshowdowColor(BackgroundColor: UIColor, showdowColor: UIColor){
        self.setBackgroundImage(imageWithColor(color: BackgroundColor), for: .default)
        self.shadowImage = imageWithColor(color: showdowColor)
        
        if #available(iOS 15.0, *) {
            let appearance = UINavigationBarAppearance()
            appearance.configureWithOpaqueBackground()
            appearance.backgroundColor = BackgroundColor
            self.standardAppearance = appearance
            self.scrollEdgeAppearance = appearance
        } else {

        }
    }
}
